package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private IUserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IFollowService followService;

    @Override
    /**
     * 分页查询
     */
    public Result queryHotBlog(Integer current) {

        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
        });

        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("用户不存在");
        }
        //查询当前用户是否被点赞
        isBlogLiked(blog);
        queryBlogUser(blog);
        return Result.ok(blog);
    }

    /**
     * 查询用户是否点赞
     *
     * @param blog
     */
    private void isBlogLiked(Blog blog) {
        String key = "blog:liked:" + blog.getId();
        //获取用户
        final UserDTO user = UserHolder.getUser();
        //如果用户未登录，无需进行点赞查询
        if (user == null) {
            return;
        }
        final Long userId = user.getId();
        //判断当前用户是否点赞
        final Double score = redisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null) { //说明未点赞
            blog.setIsLike(false);
        } else {
            blog.setIsLike(true);
        }
    }

    /**
     * 点赞
     *
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        String key = BLOG_LIKED_KEY + id;

        //1.获取登录用户ID
        final Long userId = UserHolder.getUser().getId();
        //2.判断用户是否点赞
        final Double score = redisTemplate.opsForZSet().score(key, userId.toString());//如果成员存在于有序集合中，则返回该成员的分数
        //3.若未点赞，数据库点赞数+1，并保存用户到redis的zset集合里面
        if (score == null) { //说明用户未点赞
            final boolean update = update().setSql("liked = liked + 1").eq("id", id).update();
            if (update) {
                redisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //4.若点赞，数据库点赞数-1，并将redis的zset保存的用户移除
            final boolean update = update().setSql("liked = liked - 1").eq("id", id).update();
            if (update) {
                redisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }

        return Result.ok();
    }

    /**
     * 实现点赞排行榜功能
     *
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        //1.查询Top5的点赞用户
        final Set<String> range = redisTemplate.opsForZSet().range(key, 0, 4);
        if (range == null || range.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //2.解析出其中的用户id
        final List<Long> list = range
                .stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());//通过stream流将string类型数据转换成Long类型，再输出为List集合
        //3，根据用户id查询用户
        final String userIdStr = StrUtil.join(",", list); //将List集合元素拼接成字符串，元素之间用逗号隔开。

        //TODO 未完成
        List<UserDTO> userDTOS = userService.query()
                .in("id", list).last("ORDER BY FIELD(id," + userIdStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());


        //4.返回
        return Result.ok(userDTOS);
    }

    /**
     * 保存blog
     *
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        final Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);
        final boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("新增笔记失败");
        }
        //1.保存笔记的同时，将笔记推送给粉丝
        //1.1获取粉丝
        final List<Follow> followList = followService
                                        .query()
                                        .eq("follow_user_id", userId)
                                        .list();
        //1.2推送到粉丝的收件箱里面
        for (Follow follow : followList) {
            String key = FEED_KEY + follow.getUserId();
            redisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    //实现滚动分页查询
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //todo 未完成 2025/4/1

        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2.查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        // 3.非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 4.解析数据：blogId、minTime（时间戳）、offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0; // 2
        int os = 1; // 2
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) { // 5 4 4 2 2
            // 4.1.获取id
            ids.add(Long.valueOf(tuple.getValue()));
            // 4.2.获取分数(时间戳）
            long time = tuple.getScore().longValue();
            if(time == minTime){
                os++;
            }else{
                minTime = time;
                os = 1;
            }
        }
        os = minTime == max ? os : os + offset;
        // 5.根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();

        for (Blog blog : blogs) {
            // 5.1.查询blog有关的用户
            queryBlogUser(blog);
            // 5.2.查询blog是否被点赞
            isBlogLiked(blog);
        }

        // 6.封装并返回
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);

        return Result.ok(r);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
